<template>
	<view class="cash">
		<view class="cash-top">
			<view class="leiji">可用余额</view>
			<text class="num"
				style="font-weight: bold;font-size: 60upx;color: #000;margin-bottom: 10px">￥{{ walletmoney }}</text>
			<!-- #ifdef H5 -->
			<!-- <view class="tishi">支持支付宝充值，输入充值金额，最低1元</view> -->
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<!-- <view class="tishi">支持微信、支付宝充值，输入充值金额，最低1元</view> -->
			<!-- #endif -->
		</view>
		
		<view
			style="height: max-content;background-color: #FFFFFF;box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;margin: 0upx 30upx;border-radius: 20upx;">
			<view  style="display: flex;flex-direction: row;padding: 35upx 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;">手机号码</view>
			</view>
			<view 
				style="display: flex;flex-direction: row;padding: 0upx 20upx; margin-top: 10upx;">
				<view style="font-size: 28upx;color: #333333;"></view>
				<input type="number" v-model="phone" placeholder="请输入手机号码"
					style="font-size: 30upx;color: #333333;text-align: left;margin-left: 10upx;width: 100%;" />
			</view>
			<view style="background: #E6E6E6;width: 100%;height: 1upx;"></view>
			
			<view style="width:100%;height: 1upx;margin-top: 20upx;"></view>
		
		</view>

		<view
			style="height: max-content;background-color: #FFFFFF;box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;margin: 30upx 30upx;border-radius: 20upx;">
			<view v-if="PersonType == 1" style="display: flex;flex-direction: row;padding: 35upx 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;">转账金额</view>
			</view>
			<view v-if="PersonType == 1"
				style="display: flex;flex-direction: row;padding: 0upx 20upx; margin-top: 10upx;">
				<view style="font-size: 28upx;color: #333333;">¥</view>
				<input type="number" v-model="money" placeholder="请输入金额"
					style="font-size: 30upx;color: #333333;text-align: left;margin-left: 10upx;width: 100%;" />
			</view>
			<view style="background: #E6E6E6;width: 100%;height: 1upx;"></view>
			
			<view style="width:100%;height: 1upx;margin-top: 20upx;"></view>

			<!-- <view style="display: flex;flex-direction: row;padding: 20upx;margin-top: 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;" v-if="PersonType == 1">选择充值方式</view>
				<view style="font-size: 28upx;color: #333333;font-weight: bold;" v-if="PersonType == 2">请识别下方二维码付款后联系客服
				</view>
			</view> -->

			<view style="padding: 0 20upx;" v-if="PersonType == 2">
				<image :src="wxShoukuanma" @click="previewImg(wxShoukuanma)"
					style="width: 710upx;background-size: 100%;height: 700upx;"></image>
				<image :src="zfbShoukuanma" @click="previewImg(zfbShoukuanma)"
					style="width: 710upx;background-size: 100%;height: 700upx;margin-top: 32upx;"></image>
			</view>

			<!-- <view style="padding: 0 20upx;" v-if="openLists.length > 0 && PersonType == 1">
				<view style="display: flex;height: 100upx;align-items: center;padding-bottom: 20upx;"
					v-for="(item,index) in openLists" :key='index'>
					<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
					<view style="font-size: 30upx;color: #333333;margin-left: 20upx;width: 70%;">{{item.text}}</view>
					<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item)'>
						<label class="tui-radio">
							<radio color="#FF332F" :checked="openWay === item.id ? true : false" />
						</label>
					</radio-group>
				</view>
			</view> -->
		</view>

		<button style="font-size: 36upx;background: #FF332F;height: 100upx;line-height: 100upx;margin: 60upx; border-radius: 50upx;color: #FFFFFF;" @click="transfer"
			v-if="PersonType == 1">确认转账</button>
		<!-- <view style="display: flex;width: 100%;justify-content: center;">
			<view style="color: grey;padding-bottom: 30px;padding-top: 20upx;" @click="goDetail">充值明细</view>
		</view> -->
	</view>
</template>

<script>
	import config from '../../../common/config.js'
	export default {
		data() {
			return {
				money: '',
				walletmoney: '0',
				providerList: [],
				provider: '',
				disc: '',
				wxShoukuanma: '',
				zfbShoukuanma: '',
				PersonType: 1, //1,官方  2，个人
				openWay: '1',
				wallet: [],
				CheckRechargevalue: '1',
				openLists: [],
				
				from: '',
				userId:''
			};
		},
		onShow() {
			this.userId = this.$queue.getData('openid');
			if ('mall' == this.from) {
				console.log('from mall...')
				this.getMyInfo()
			}else{
				this.getwalletMoney();
			}
			
		},
		onLoad(params) {
			this.from = params.from
			this.userId = this.$queue.getData('openid');
			this.getCheckRecharge();
			if (params.title) {
				uni.setNavigationBarTitle({
					title: params.title
				})
			}
			this.getwalletMoney();
			this.shoukuanma();

			this.$Request.getT('/common/type/172').then(res => {
				if (res.code === 0) {
					if (res.data.value === '2') {
						this.PersonType = 2;
					} else {
						this.PersonType = 1;
					}
				}
			});

			uni.getProvider({
				service: 'payment',
				success: e => {
					console.log('payment success:' + JSON.stringify(e));
					let providerList = [];
					e.provider.map(value => {
						switch (value) {
							case 'alipay':
								providerList.push({
									name: '支付宝',
									id: value,
									loading: false
								});
								break;
							case 'wxpay':
								providerList.push({
									name: '微信',
									id: value,
									loading: false
								});
								break;
							default:
								break;
						}
					});
					this.providerList = providerList;
				},
				fail: e => {
					console.log('获取支付通道失败：', e);
				}
			});
		},
		methods: {
			getMyInfo() {
				
				uni.request({
					// url: 'https://k999az04ootw.ngrok2.xiaomiqiu.cn/p/user/newUserInfo/' + this.userId,
					url: config.mallHost+'/p/user/newUserInfo/' + this.userId,
					method: 'GET',
					success: (res) => {
						console.log('信息', res)
						uni.hideLoading()
						this.walletmoney = res.data.money
					},
					fail: (err) => {
						console.log('err', err)
					}
				})
			},
			//转账
			transfer() {
				let data = {
					amount:this.money,
					phone:this.phone,
					userId:this.userId
				}
				console.log('转账参数：',data)
				console.log('转账参数url：',config.mallHost)
				uni.request({
					// url: 'https://k999az04ootw.ngrok2.xiaomiqiu.cn/p/order/recharge',
					url: config.mallHost+'/p/order/transfer',
					method: 'POST',
					header: {
						"Content-Type": "application/json", //自定义请求头信息
						"userId":this.userId
					},
					data:data,
					success: (res) => {
						console.log('转账信息', res)
						if(res.data&&res.data.statusCodeValue==400){
							uni.showToast({
								title:res.data.body,
								icon:'none',
								duration:2000
							})
							return
						}
						if(!res.data&&res.statusCode==200){
							uni.showToast({
								title:'转账成功',
								icon:'none',
								duration:2000
							})
							// this.getMyInfo()
							uni.navigateBack({
								delta:1
							})
						}
						
					},
					fail: (err) => {
						console.log('err', err)
					}
				})
			},
			previewImg(logourl) {
				let _this = this;
				let imgsArray = [];
				imgsArray[0] = logourl;
				uni.previewImage({
					current: 0,
					urls: imgsArray
				});
			},
			shoukuanma() {
				//微信收款码
				this.$Request.getT('/common/type/173').then(res => {
					if (res.code === 0) {
						this.wxShoukuanma = res.data.value;
					}
				});

				//支付宝收款码
				this.$Request.getT('/common/type/174').then(res => {
					if (res.code === 0) {
						this.zfbShoukuanma = res.data.value;
					}
				});
			},
			getCheckRecharge() {
				this.$Request.getT('/common/type/97').then(res => {
					if (res.code === 0) {
						this.CheckRechargevalue = res.data.value; //1,企业	2，个人
						this.openLists = [];
						if (res.data.value == 1) {
							// #ifndef H5
							this.disc = '支持微信、支付宝充值，输入充值金额，最低1元';
							let data = {};
							data.id = '2';
							data.image = '../../static/img/my/zhifubao.png';
							data.text = '支付宝';
							this.openLists.push(data);
							let data1 = {};
							data1.id = '1';
							data1.image = '../../static/share/icon_weixin.png';
							data1.text = '微信';
							this.openLists.push(data1);
							// #endif
							// #ifdef H5
							let target = navigator.userAgent.toLowerCase();
							let ua = navigator.userAgent.toLowerCase();
							this.openLists = [];
							if (ua.indexOf('micromessenger') !== -1) {
								this.disc = '支持微信充值，输入充值金额，最低1元';
								this.openWay = '2';
								let data1 = {};
								data1.id = '2';
								data1.image = '../../static/share/icon_weixin.png';
								data1.text = '微信';
								this.openLists.push(data1);
							} else {
								this.disc = '支持支付宝充值，输入充值金额，最低1元';
								this.openWay = '1';
								let data = {};
								data.id = '1';
								data.image = '../../static/img/my/zhifubao.png';
								data.text = '支付宝';
								this.openLists.push(data);
							}
							// #endif
						} else {
							this.disc = '支持支付宝充值，输入充值金额，最低1元';
							this.openWay = '1';
							let data = {};
							data.id = '1';
							data.image = '../../static/img/my/zhifubao.png';
							data.text = '支付宝';
							this.openLists.push(data);
						}
					}
				});
			},
			selectWay: function(item) {
				this.openWay = item.id;
				console.log('支付方式：',this.openWay)
			},
			//获取获取额度
			goDetail() {
				uni.navigateTo({
					url: './rechargeDetail'
				});
			},
			getwalletMoney() {
				// let userId = this.$queue.getData('userId');
				let userId = this.$queue.getData('openid');
				this.$Request.getJ('userMoney/selectUserMoney?userId=' + userId).then(res => {
					if (res.code === 0) {
						this.walletmoney = res.data.cannotMoney;
						this.wallet.push(res.data);
					}
					uni.hideLoading();
				});
			},
			//商城充值
			rechargeMall() {
				let data = {
					amount:this.money,
					payType:1
				}
				console.log('充值参数：',data)
				console.log('充值参数url：',config.mallHost)
				uni.request({
					// url: 'https://k999az04ootw.ngrok2.xiaomiqiu.cn/p/order/recharge',
					url: config.mallHost+'/p/order/recharge',
					method: 'POST',
					header: {
						"Content-Type": "application/json", //自定义请求头信息
						"userId":this.userId
					},
					data:data,
					success: (res) => {
						console.log('订单信息', res)
						// this.walletmoney = res.data.money
						this.wxinPay(res)
						
					},
					fail: (err) => {
						console.log('err', err)
					}
				})
			},
			recharge() {
				// if (!/^\d+$/.test(this.money)) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '请输入正确金额，不能包含中文，英文，特殊字符和小数'
				// 	});
				// 	return;
				// }
				// if (this.money < 1) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '金额必须大于1元'
				// 	});
				// 	return;
				// }
				if (this.openWay == undefined) {
					uni.showToast({
						icon: 'none',
						title: '请选择支付方式'
					});
					return;
				}
				uni.showLoading({
					title: '支付中...'
				});
				if ("mall" == this.from) {
					console.log('商城充值...')
					this.rechargeMall()
					return
				}
				// let userId = this.$queue.getData('userId');
				let userId = this.$queue.getData('openid');
				if (this.CheckRechargevalue == '1') {
					//1，支付宝，2，微信
					if (this.openWay == '1') {
						// #ifdef H5
						this.$Request.postT('/api/aliPay/payH5?money=' + this.money + '&userId=' + userId).then(res => {
							if (res.code === 0) {
								const div = document.createElement('div')
								div.innerHTML = res.data //此处form就是后台返回接收到的数据
								document.body.appendChild(div)
								document.forms[0].submit()
							} else {
								uni.showToast({
									icon: 'none',
									title: '支付失败!'
								});
							}
						});
						// #endif
						// #ifdef MP
						this.$Request.postJson('/api/aliPay/payApp?userId=' + userId + '&money=' + this.money).then(
							res => {
								console.log("确认支付 ali mp: ", res);
								// this.isCheckPay(res.code, 'alipay', res.data);
								this.aliPay(res)
							});
						// #endif
						// #ifdef APP
						this.$Request.postJson('/api/aliPay/payApp?userId=' + userId + '&money=' + this.money).then(
							res => {
								console.log("确认支付: ", res);
								this.isCheckPay(res.code, 'alipay', res.data);
							});
						// #endif

					} else if (this.openWay == '2') {
						// #ifdef H5
						this.$Request.postJson('/api/order/wxPayJsApi?userId=' + userId + '&money=' + this.money * 100)
							.then(res => {
								console.log("确认支付 H5: ", res);
								this.callPay(res);
							});
						// #endif
						// #ifdef MP
						this.$Request.postJson('/api/order/wxPayJsApi?userId=' + userId + '&money=' + this.money * 100)
							.then(res => {
								console.log("确认支付 MP: ", res);
								// this.callPay(res);
								this.wxPay(res)
							});
						// #endif
						// #ifdef APP
						console.log("userId: " + userId);
						console.log("money: " + this.money * 100);
						this.$Request.postJson('/api/order/wxPayApp?userId=' + userId + '&money=' + this.money * 100).then(
							res => {
								console.log("确认支付 微信: ", res);
								this.isCheckPay(res.code, 'wxpay', JSON.stringify(res.data));
							});
						// #endif
					}
				} else if (this.CheckRechargevalue == '2') {
					// #ifndef H5
					this.$Request.postJson('/api/aliPay/payApp?userId=' + userId + '&money=' + this.money).then(res => {
						this.isCheckPay(res.code, 'alipay', res.data);
					});
					// #endif
					// #ifdef H5
					this.$Request.postT('/api/aliPay/payH5?money=' + this.money + '&userId=' + userId).then(res => {
						if (res.code === 0) {
							const div = document.createElement('div')
							div.innerHTML = res.data //此处form就是后台返回接收到的数据
							document.body.appendChild(div)
							document.forms[0].submit()
						} else {
							uni.showToast({
								icon: 'none',
								title: '支付失败!'
							});
						}
					});
					// #endif
				} else {
					this.$Request.postJson('/pays/pay?price=' + this.money + '&istype=' + this.openWay + '&userId=' +
						userId).then(
						res => {
							if (res.data) {
								let data = res.data;
								var url = 'https://pay.paysapi.com?goodsname=' + data.goodsname + '&istype=' + data
									.istype + '&key=' + data.key +
									'&notify_url=' + data
									.notify_url + '&orderid=' + data.orderid + '&price=' + data.price +
									'&return_url=' + data.return_url +
									'&uid=' + data.uid + '&orderuid=' + data.orderuid;
								this.$queue.setData('rechargeUrl', url);
								uni.navigateTo({
									url: '../member/webview?url=' + url
								});
							}
						});
				}
			},
			callPay: function(response) {
				if (typeof WeixinJSBridge === "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
					}
				} else {
					this.onBridgeReady(response);
				}
			},
			onBridgeReady: function(response) {
				let that = this;
				if (!response.package) {
					return;
				}
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							uni.showLoading({
								title: '支付成功'
							});
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							uni.hideLoading();
						}
						WeixinJSBridge.log(response.err_msg);
					}
				);
			},
			isCheckPay(code, name, order) {
				if (code === 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误'
					});
				}
			},
			wxinPay(res) {
				var orderInfo = res.data;
				console.log('支付参数：',orderInfo)
				// 微信支付
				uni.requestPayment({
					provider: "wxpay",
					orderInfo: orderInfo,
					success:(res)=> {
						console.log("支付 res: ",res);
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(this.getMyInfo(), 2000);
					},
					fail:(err)=> {
						console.log("支付 err: ",err);
					}
				})
			},
			wxPay(res){
				console.log("微信支付...");
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: res.timestamp,
					nonceStr: res.noncestr,
					package: res.package,
					signType: res.signType,
					paySign: res.sign,
					success: (res)=> {
						console.log("支付 res: ",res);
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(this.getwalletMoney(), 3000);
					},
					fail: (err)=> {
						console.log("支付 err: ",err);
					}
				})
			},
			aliPay(res){
				uni.requestPayment({
					provider: 'alipay',
					orderInfo: res.data.third.trade_no,
					success: (res)=> {
						console.log("支付成功: ",res);
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(this.getwalletMoney(), 3000);
					},
					fail: (err)=> {
						console.log("支付 err: ",err);
					}
				})
			},
			setPayment(name, order) {
				console.log("支付参数name: ", name);
				console.log("支付参数order: ", order);
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					success: function(res) {
						console.log("支付res: ", res);
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(this.getwalletMoney(), 3000);
					},
					fail: function(err) {
						console.log("支付err: ", err);
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			},



		}
	};
</script>

<style lang="less" scoped>
	@import '../../static/css/index.css';

	page {
		background: #FFFFFF;
	}

	#shareit {
		-webkit-user-select: none;
		position: fixed;
		/*width: 100%;*/
		height: 2000px;
		background: rgba(0, 0, 0, 0.85);
		text-align: center;
		top: 0;
		left: 0;
		z-index: 999;
	}

	#shareit img {
		max-width: 100%;
	}

	.arrow {
		width: 100px;
		height: 150px;
		position: absolute;
		right: 5%;
		top: 1%;
	}

	#follow {
		margin-right: 60px;
		margin-left: 30px;
		width: 90%;
		height: 50px;
		line-height: 50px;
		text-align: left;
		text-decoration: none;
		font-size: 18px;
		color: white;
		float: left;
		margin-top: 160px;
	}

	.cash {
		position: absolute;
		// background-image: url(../../static/img/my/rechargeback.jpg);
		background-image: linear-gradient(to right, #ff6d01, #e64340);
		background-size: 100%;
		width: 100%;
		height: 225upx;
		border-bottom-left-radius: 20upx;
		border-bottom-right-radius: 20upx;


		.cash-top {
			border-radius: 20upx;
			margin: 80upx 0 30upx 30upx;
			height: 260upx;
			padding: 30upx 0 70upx 30upx;
			width: 650upx;
			box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;
			/* border-bottom: 1px solid gainsboro; */
			//background: #e64340;
			//background-image: url(../../static/img/my/rechargeback.png);
			background: #FFFFFF;
			background-size: 100%;

		}

		.leiji {
			font-size: 24upx;
			color: #000;
			margin-bottom: 10px;
		}

		.tishi {
			margin-top: 25upx;
			font-size: 24upx;
			color: #000;
			margin-bottom: 10px;
		}
	}

	.tui-radio {
		display: inline-block;
		padding-left: 28rpx;
		font-size: 36rpx;
		vertical-align: middle;
	}

	.myRadio {
		// height: 16upx;
		// width: 16upx;
		margin-top: 16upx;
		margin-right: 16upx;
	}
</style>
